<template>
  <div class="chat-main">
    <li-header @headerLeftEvent="loginEvent" @headerRightEvent="configEvent" :config="headerConfig">
      <div slot="title" class="header-title" @click="headCenterEvent">{{userInfo.username}} <span style="fontSize: 12px;">▼</span>
      </div>
    </li-header>
    <div class="content" @click="panelShow = false" ref="scroll">
            <div class="height-hook">
                <div v-for="(item, index) in messageList">
                    <div class="item-box left-hook" v-if="item.type === 2">
                        <div class="left">
                          <img :src="`${avatarPrefix}/${item.msgUser.avatar}`"/>
                        </div>
                        <chat-slot :chatdata="item"></chat-slot>
                    </div>
                    <div class="item-box right-hook" v-if="item.type === 3">
                        <div class="right">
                          <img :src="`${avatarPrefix}/${item.msgUser.avatar}`"/>
                        </div>
                        <chat-slot :chatdata="item"></chat-slot>
                    </div>
                    <div class="item-box center-hook" v-if="item.type === 1">
                        <span class="tip">{{ item.msg.content }}</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer" :class="{'panel-show': panelShow}">
            <div class="main">
                <input type="text" @focus="updated" class="input" v-model="inputValue" @keyup.enter="sendMessage" v-show="connectState"/>
                <input type="text" class="input" disabled v-show="!connectState" v-model="inputValue"/>
                <div panelname="emoji" @click.stop.prevent="togglePanel" class="chat-slot">
                  <md-icon panelname="emoji" class="md-primary emoji-toggle">mood</md-icon>
                </div>
                <div panelname="utils" @click="togglePanel" v-if="(inputValue == '')" class="chat-slot">
                  <md-icon panelname="utils" class="md-primary emoji-toggle">add</md-icon>
                </div>
                <div v-if="!(inputValue == '')" class="send" :class="{logout: !connectState}" @click="sendMessage">发送</div>
            </div>
            <div class="emoji-panel" v-show="(panelName === 'emoji')">
              <ul class="emoji-list">
                <li @click="setEmoji" :alt="item.char" class="emoji-wrapper js-emoji" v-for="(item, index) in emojiSheet">
                  <div class="emoji-code">{{item.char}}</div>
                </li>
              </ul>
            </div>
            <div v-show="(panelName === 'utils')" class="util-panel">
              <ul class="utils-list">
                <li @click="getFile" class="photo-transfer">
                  <md-icon class="md-primary">photo</md-icon>
                  <input accept="image/*" id="file-input" type="file" style="display:none">
                </li>
                <li class="photo-camera">
                  <md-icon class="md-primary">photo_camera</md-icon>
                </li>
                <li @click="getLocation" class="user-position">
                  <md-icon class="md-primary">room</md-icon>
                </li>
              </ul>
            </div>
        </div>
        <div class="shot-container">
          <div id ="camera-container">

          </div>
        </div> 
        <li-model ref="pop" type="pop" class="userList">
            <div slot="modalbody">
                <h5>群组成员列表</h5>
                <ul>
                    <li v-for="(item, index) in onlineUserList">
                        <div class="box">
                            <img :src="`${avatarPrefix}/${item.avatar}`" />
                            <div class="name">{{ item.username }}</div>
                        </div>
                    </li>
                </ul>
            </div>
            <div slot="modelfoot"></div>
        </li-model>
        <li-model ref="confirm" type="confirm" @confirmEvent="confirmBtnEvent">
            <div slot="confirm"> 您当前未连接群聊。点击确定即可加入！</div>
        </li-model>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import io from 'socket.io-client'
import {url} from './../../service/getData'
import header from './children/header'
import model from './children/model'
import chatslot from './children/chatslot'
import twemoji from 'twemoji'
import {emoji} from './../../config/emoji'
import FileAPI from 'fileapi'
export default {
  data () {
    return {
      messageList: [],
      onlineUserList: [],
      connectState: false,
      userInfo: {},
      headerConfig: {
        left: 'conn',
        right: '设置'
      },
      inputValue: '',
      panelShow: false,
      emojiSheet: emoji,
      panelName: ''
    }
  },
  components: {
    'li-header': header,
    'li-model': model,
    'chat-slot': chatslot
  },
  computed: {
    ...mapState([
      'common'
    ]),
    avatarPrefix () {
      return process.env.NODE_ENV === 'development' ? 'ehmaster' : 'http://nb.tmallup.cn/ehentai-master/static'
    }
  },
  created () {
    this.userInfo = {}
    this.messageList = [] // type = 1 提示信息     type = 2 对方内容     type = 3 我发送内容
  },
  mounted () {
    FileAPI.media = true
    FileAPI.staticPath = '/static/FileAPI'
    this.connectEvent()
    twemoji.parse(document.querySelector('.emoji-list'))
    this.inputChange()
  },
  methods: {
    connectEvent () {
      this.userInfo = {
        id: this.getUserId(),
        username: this.common.userInfo.username,
        avatar: this.common.userInfo.avatar
      }
      this.httpServer = io.connect(`${url}/room`)
      this.httpServer.emit('login', this.userInfo)
      this.httpServer.on('login', (obj) => {
        this.onlineUserList = obj.onlineUserList
        this.onMessage(obj, '用户 ' + obj.msgUser.username + ' 加入聊天', 1, 'text')
      })
      this.httpServer.on('loginSuccess', (obj) => {
        if (obj.sign === 1) {
          this.onlineUserList = obj.onlineUserList
          this.connectState = true
          this.headerConfig.left = this.userInfo.avatar
          console.log('连接好了')
        }
      })
      this.httpServer.on('logout', (obj) => {
        this.onMessage(obj, '用户 ' + obj.msgUser.username + ' 退群了', 1, 'text')
      })
      this.httpServer.on('message', (obj) => {
        var isMe = obj.user.id === this.userInfo.id
        if (isMe) {
          this.updateMsgStatus(obj.msgToken)
        } else {
          this.onMessage(obj, obj.msg.content, 2, obj.msg.mesType)
        }
        this.onlineUserList = obj.onlineUserList
        this.$nextTick(function () {
          twemoji.parse(document.querySelector('.content'), {className: 'emoji-chat'})
        })
      })
    },
    updateMsgStatus (msgToken) {
      this.messageList.forEach(function (item, i) {
        if (item.msgToken === msgToken) {
          item.status = 'finish'
        }
      })
    },
    getUserId () {
      return (new Date().getTime() + '' + Math.floor(Math.random() * 100000 + 100)) - 0
    },
    getMessageToken () {
      return this.userInfo.username + new Date().getTime() + '' + Math.floor(Math.random() * 100000 + 100)
    },
    onMessage (obj, msg, type, mesType) {
      this.messageList.push({type, msg: {content: msg, mesType}, msgUser: obj.user})
    },
    configEvent () {
      console.log('聊天室设置触发事件')
    },
    loginEvent () {
      console.log('加入聊天室事件')
      console.log(this.connectState)
      if (!this.connectState) {
      }
    },
    headCenterEvent () {
      if (this.connectState) {
        console.log('弹出群组全部成员弹窗事件')
        console.log(this.getMessageToken())
        this.$refs.pop.modelOpen()
        console.log(this.onlineUserList)
      }
    },
    updated () {
      setTimeout(() => {
        this.scroll()
      }, 300)
    },
    sendMessage () {
      this.inputValue = this.trim(this.inputValue)
      if (this.inputValue.length > 0) {
        if (this.connectState) {
          var msgToken = this.getMessageToken()
          this.messageList.push({type: 3, msg: {content: this.inputValue, mesType: 'text'}, msgUser: this.userInfo, status: 'pending', msgToken})
          this.httpServer.emit('message', {msg: {content: this.inputValue, mesType: 'text'}, user: this.userInfo, msgToken})
          this.inputValue = ''
        } else {
          this.$refs.confirm.modelOpen()
        }
      }
    },
    inputChange () {
      var el = document.getElementById('file-input')
      var msgToken = this.getMessageToken()
      FileAPI.event.on(el, 'change', (evt) => {
        var file = FileAPI.getFiles(evt)[0]
        if (file.size > 5242880) {
          window.notie.alert({
            type: 'error',
            text: '图片请小于5MB蟹蟹合作'
          })
          return
        }
        FileAPI.readAsDataURL(file, (result) => {
          if (result.type === 'load') {
            this.messageList.push({type: 3, msg: {content: result.result, mesType: 'image'}, msgUser: this.userInfo, status: 'pending', msgToken})
            this.httpServer.emit('message', {msg: {content: result.result, mesType: 'image'}, user: this.userInfo, msgToken})
          }
        })
      })
    },
    getFile () {
      document.getElementById('file-input').click()
    },
    trim (s) {
      return s.replace(/(^\s*)|(\s*$)/g, '')
    },
    scroll () {
      this.$refs.scroll.scrollTop = this.$refs.scroll.scrollHeight
    },
    confirmBtnEvent (num) {
      if (num === 1) {
        this.connectEvent()
      }
    },
    togglePanel (e) {
      this.panelName = e.target.attributes.panelname.value
      console.log(this.panelName)
      this.panelShow = true
      this.$nextTick(function () {
        this.updated()
      })
    },
    setEmoji (e) {
      this.inputValue += e.target.attributes.alt.value
    },
    getLocation () {
      const onSuccess = (e) => {
        var msgToken = this.getMessageToken()
        this.messageList.push({type: 3, msg: {content: {latitude: e.coords.latitude, longitude: e.coords.longitude}, mesType: 'position'}, msgUser: this.userInfo, status: 'pending', msgToken})
        this.httpServer.emit('message', {msg: {content: {latitude: e.coords.latitude, longitude: e.coords.longitude}, mesType: 'position'}, user: this.userInfo, msgToken})
      }
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true })
      } else {
        window.notie.alert({
          type: 'error',
          text: '您的设备好像不支持定位功能'
        })
      }
      function onError (e) {
        window.notie.alert({
          type: 'error',
          text: '定位失败了,待会再试试吧'
        })
      }
    }
  }
}
</script>

<style lang="less">
    .chat-main {
        font-family: "Microsoft YaHei";
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        .header-title {
            text-align: center;
        }
        .content {
            width: 100%;
            display: flex;
            flex: 1;
            padding: 10px;
            box-sizing: border-box;
            overflow-y: auto;
            background: #EDEDED;
            .height-hook{
              width: 100%;
            }
            .item-box {
                width: 100%;
                margin-bottom: 10px;
                .left {
                    float: left;
                    width: 40px;
                    img {
                        height: 40px;
                        border-radius: 50%;
                    }
                }
                .right {
                    float: right;
                    width: 40px;
                    img {
                        height: 40px;
                        border-radius: 50%;
                    }
                }
                .center {
                    max-width: 65%;
                    .text {
                      position: relative;
                      font-size: 13px;
                      padding: 8px 10px 5px 10px;
                      border-radius: 3px;
                      line-height: 20px;
                    }
                    .horn {
                      content: '';
                      position: absolute;
                    }
                }
                &.center-hook {
                    text-align: center;
                    padding: 15px 0;
                    .tip {
                        padding: 3px 6px;
                        border-radius: 2px;
                        background: rgba(0, 0, 0, 0.2);
                        color: #fff;
                        font-size: 12px;
                        line-height: 12px;
                    }
                }
            }
            .left-hook {
                .center {
                    float: left;
                    margin-left: 10px;
                    .text {
                      background: #fff;
                      color: #333;
                    }
                    .horn {
                      width: 0;
                      height: 0;
                      left: -7px;
                      top: 5px;
                      border-top: 8px solid transparent;
                      border-right: 9px solid #fff;
                      border-bottom: 8px solid transparent;
                    }
                    .user {
                        margin-bottom: 5px;
                        font-size: 12px;
                        color: #aaa;
                        line-height: 12px;
                    }
                }
            }
            .right-hook {
                .center {
                    float: right;
                    text-align: right;
                    margin-right: 10px;
                    .text {
                      background: #499eff;
                      color: #fff;
                    }
                    .horn {
                      color: #499eff;
                      top: 5px;
                      right: -7px;
                      width: 0;
                      height: 0;
                      border-top: 8px solid transparent;
                      border-left: 9px solid #499EFF;
                      border-bottom: 8px solid transparent;
                        }
                    .user {
                        text-align: right;
                        margin-bottom: 5px;
                        font-size: 12px;
                        color: #aaa;
                        line-height: 12px;
                    }
                }
            }
        }
        .userList {
            h5 {
                margin: 0;
                padding-top: 15px;
                line-height: 25px;
                text-align: center;
                color: #444;
            }
            ul {
                padding: 15px 0;
                margin: 0 auto;
                width: 90%;
                font-size: 0;
                li {
                    width: 25%;
                    display: inline-block;
                    .box {
                        width: 80%;
                        margin: 0 auto;
                        padding-bottom: 5px;
                        img {
                            width: 100%;
                        }
                        .name {
                            width: 100%;
                            text-align: center;
                            line-height: 16px;
                            color: #888;
                            font-size: 12px;
                        }
                    }
                }
            }
        }
        .footer {
            width: 100%;
            display: flex;
            flex: 0 0 50px;
            background: #fff;
            border-top: 1px solid #dedede;
            padding: 8px 10px;
            box-sizing: border-box;
            flex-direction: column;
            .main {
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: row;
                flex: 0 0 34px;
                .input {
                    height: 34px;
                    outline: none;
                    border: 1px solid #ddd;
                    background: #efefef;
                    padding: 0;
                    box-sizing: border-box;
                    border-radius: 5px 0 0 5px;
                    text-indent: 10px;
                    color: #444;
                    font-size: 14px;
                    display: flex;
                    flex: 0 0 70%;
                    font-family: "Microsoft YaHei";
                    &:focus {
                        border: 1px solid #ccc;
                    }
                }
                .chat-slot{
                  display: flex;
                  flex: 0 0 15%;
                  .emoji-toggle {
                    width: 34px;
                    min-width: 34px;
                    height: 34px;
                    min-height: 34px;
                    font-size: 34px;
                    margin: 0
                  }
                }
                .send {
                    height: 34px;
                    outline: none;
                    background: #499eff;
                    border-radius: 5px;
                    box-sizing: border-box;
                    text-align: center;
                    line-height: 34px;
                    color: #fff;
                    display: flex;
                    flex: 0 0 15%;
                    cursor: pointer;
                    justify-content: center;
                    &.logout {
                        background: #aaa;
                    }
                }
            }
            .emoji-panel, .util-panel{
              display: flex;
              overflow: auto;
              flex: 1;
              height: 100%;
              .utils-list {
                display: flex;
                flex: 1;
                flex-direction: row;
                li {
                  display: flex;
                  flex: 1;
                  i {
                    width: 3rem;
                    min-width: 3rem;
                    height: 3rem;
                    min-height: 3rem;
                    font-size: 3rem;
                  }
                }
              }
            }
        }
        .panel-show {
          flex: 0 0 10rem;
        }
    }
    .emoji-list {
      line-height: 0;
      .emoji-wrapper {
        width: auto;
        padding: 8px;
        display: inline-block;
        overflow: hidden;
        white-space: nowrap;
        .emoji-code {
          width: 1.2rem;
          height: 1.2rem;
        }
      }
    }
</style>

<style>
.emoji-chat {
  width: 20px;
  margin-left: 5px
}
</style>
